package com.ithaipeng.redanttakeaway.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ithaipeng.redanttakeaway.pojo.Employee;
import com.ithaipeng.redanttakeaway.service.IEmployeeService;
import com.ithaipeng.redanttakeaway.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

@RestController
@Slf4j
@RequestMapping(path = "/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    //登录一定是post请求
    @PostMapping(path = "/login")
    public Result<Employee> login(HttpServletRequest request,
                                  @RequestBody Employee employee){
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        //获取前端来到密码，并于数据库的进行比较，且已经进行md5转换
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);
        //先判断账户是否存在
        if(emp==null){
            return Result.error("账户或者密码错误!,请重试");
        }if(!emp.getPassword().equals(password)){
            return Result.error("账户或者密码错误!,请重试");
        }
        //此上，两个return都没有走的话，那么表示登录成功,将id存入session中
        request.getSession().setAttribute("empId",emp.getId());
        return Result.success(emp);
    }
    //退出请求
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("msgId");
        return Result.success("退出成功!");
    }
    @PostMapping
    public Result<String> save(@RequestBody Employee employee,HttpServletRequest request){
        log.info("employee:{}",employee.toString());
        // 添加密码，并将其进行加密，默认密码就是123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        boolean isSuccess = employeeService.save(employee);
        if (isSuccess){
            return Result.success("添加员工信息成功");
        }else {
            return Result.error("添加员工信息失败");
        }
    }

    /**
     * 分页查询
     * @param page 第几页
     * @param pageSize  每页多少体
     * @param name 姓名
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Employee>> pageInfo(@RequestParam(required = false,defaultValue ="1") Integer page,
                                           @RequestParam(required = false,defaultValue = "10")Integer pageSize,
                                           String name){
        //分页构造器
        Page<Employee> pageTool =new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行分页查询
        employeeService.page(pageTool,queryWrapper);
        return Result.success(pageTool);
    }
    @PutMapping
    public Result<String> enableOrDisable(@RequestBody Employee employee,HttpServletRequest request){
        boolean isSuccess = employeeService.updateById(employee);
        if (isSuccess){
            return Result.success("修改员工账号状态成功!");
        }else {
            return Result.error("修改员工账号状态失败!");
        }
        /*
        切记，由于javaScript对long整型取值有问题，所有要配置对象映射器
         */
    }
    //编辑员工，让数据回显
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id){
        log.info("编辑员工的id为--->{}",id);
        Employee employee = employeeService.getById(id);
        if (employee!=null){
            return Result.success(employee);
        }else {
            return Result.error("数据回显失败!");
        }
    }
}
